<?php

namespace App\Service\ChatGroup;

use App\Enums\BaseErrorCode;
use App\Exceptions\Custom\ResponseHttpException;
use App\Library\Lock\NxLock;
use App\Models\ChatGroup\ChatGroupDataStatisticsModel;
use App\Models\ChatGroup\ChatGroupFAQModel;
use App\Models\ChatGroup\ChatGroupHistoryModel;
use App\Models\ChatGroup\ChatGroupModel;
use App\Models\ChatGroup\ChatGroupSessionAppraiseModel;
use App\Models\ChatGroup\ChatGroupSessionModel;
use App\Models\ChatGroup\ChatGroupUserModel;
use App\Models\Common\ConfigModel;
use App\Models\Common\HolidayModel;
use App\Service\BaseService;
use App\Service\OpenShop\User\RmsUserService;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Kuafu\GeneralFs\BuildFs;
use function Symfony\Component\Translation\t;

class ChatGroupSessionService extends BaseService
{
    const FROM_APP = 1;
    const FROM_WEB = 2;

    /**
     * 获取会话id & 尝试创建
     * @param int $shopId
     * @param int $groupId
     * @param int $from
     * @param int $userId
     * @return array
     * @throws Exception
     */
    public function enterSession(int $shopId, int $groupId, int $from, int $userId): array
    {
        if ($from == self::FROM_APP) {
            $tryCreateSession = true;
        } else {
            $tryCreateSession = false;
        }

        // 获取会话id
        $session       = $this->getSession($shopId, $groupId, $from, $tryCreateSession);
        $sessionModel  = $session['session'];
        $sessionCreate = $session['create'];

        $shopId = $session['session']->shopId;

        // 创建了新的会话 - 推送默认开场文案
        if ($sessionCreate && ($session['session']->robotIn == ChatGroupSessionModel::ROBOT_IN_YES || !ChatGroupSessionService::getAiSwitch())) {
            dispatch(function () use ($groupId, $shopId, $sessionModel) {

                // 发送群消息
                // 开场文案
                $obj = (new ChatGroupStructService($groupId, $shopId));

                $obj->sendMsgStruct(ChatGroupUserModel::KUA_XIAO_FU_USER_ID, '', ChatGroupHistoryModel::TYPE_TEXT,
                    '您好，这里是您的专属服务群，请问有什么可以帮您？', $sessionModel->id, 0,
                    ChatGroupHistoryModel::IS_SEND_AI_NO, ChatGroupHistoryModel::IS_RECORD_COUNT_NO)
                    ->send();

                // 常见问题
                $obj->sendMsgStruct(ChatGroupUserModel::KUA_XIAO_FU_USER_ID, '', ChatGroupHistoryModel::TYPE_FAQ,
                    ChatGroupFAQModel::faq(false),
                    0, 0, ChatGroupHistoryModel::IS_SEND_AI_NO, ChatGroupHistoryModel::IS_RECORD_COUNT_NO)
                    ->send();
            })
                ->delay(1)
                ->onQueue(ChatGroupStructService::QUEUE_NAME);
        }

        if ($sessionModel->serveIn == ChatGroupSessionModel::SERVE_IN_YES) {
            $serveUid  = $sessionModel->serveUid;
            $serveName = $sessionModel->serveName;
        } else {
            $serveUid  = 0;
            $serveName = '';
        }

        // 会话状态
        return [
            'sessionId' => $sessionModel->id,
            'robotIn'   => $sessionModel->robotIn,
            'serveIn'   => $sessionModel->serveIn,
            'status'    => $sessionModel->status,
            'serveUid'  => $serveUid,
            'serveName' => $serveName,
            'inGroup'   => ChatGroupUserModel::inGroup($groupId, $userId),
        ];
    }

    /**
     * 获取、创建会话id
     * @param int $shopId
     * @param int $groupId
     * @return array
     */
    private function getSession(int $shopId, int $groupId, int $from, bool $tryCreateSession = true): array
    {
        // 校验群聊Id
        $group = ChatGroupModel::query()
                               ->where('id', $groupId)
                               ->when($from != self::FROM_WEB, function ($query) use ($shopId) {
                                   $query->where('shopId', $shopId);
                               })
                               ->where('type', ChatGroupModel::TYPE_CUSTOMER_SERVE)
                               ->first();
        if (!$group) {
            self::throwErr('不存在的群聊id');
        }

        $shopId = $group->shopId;

        // 最后一条session
        $lastSession = ChatGroupSessionModel::query()
                                            ->where('groupId', $groupId)
                                            ->where('isNew', ChatGroupSessionModel::IS_NEW_YES)
                                            ->where('status', ChatGroupSessionModel::STATUS_OK)
                                            ->orderByDesc('id')
                                            ->first();

        // 找到并返回session
        if ($lastSession) {
            return ['session' => $lastSession, 'create' => false];
        }

        // 不尝试创建session
        if (!$tryCreateSession) {

            // 取默认的空session
            $session          = ChatGroupSessionModel::query()->find(0);
            $session->shopId  = $shopId;
            $session->groupId = $group;
            $session->robotIn = ChatGroupSessionModel::ROBOT_IN_YES;

            return [
                'session' => $session,
                'create'  => false,
            ];
        }

        $closureDo = function () use ($shopId, $groupId) {
            DB::beginTransaction();

            $serveIn = ChatGroupSessionModel::SERVE_IN_NO;
            $robotIn = (int)self::getAiSwitch();

            // 创建session
            $session = ChatGroupSessionModel::query()
                                            ->create([
                                                'groupId'     => $groupId,
                                                'shopId'      => $shopId,
                                                'isNew'       => ChatGroupSessionModel::IS_NEW_YES,
                                                'lastMsgTime' => time(),
                                                'robotIn'     => $robotIn,
                                                'serveIn'     => $serveIn,
                                                'status'      => ChatGroupSessionModel::STATUS_OK,
                                            ]);

            // 把其他的session都设置为旧的
            ChatGroupSessionModel::query()
                                 ->where('groupId', $groupId)
                                 ->where('id', '<>', $session->id)
                                 ->update([
                                     'isNew' => ChatGroupSessionModel::IS_NEW_NO,
                                 ]);

            DB::commit();

            return $session;
        };

        $closureReTry = function () use ($shopId, $groupId, $from, $tryCreateSession) {
            return $this->getSession($shopId, $groupId, $from, $tryCreateSession);
        };

        return [
            'session' => (new NxLock())->nx($closureDo, $closureReTry,
                NxLock::generateLockKey(__CLASS__ . '_' . __FUNCTION__, ...[$groupId])),
            'create'  => true
        ];
    }


    /**
     * 新增会话评价
     * @param int $shopId
     * @param int $msgId
     * @param int $score
     * @param int $solve
     * @param int $groupId
     * @param int $operatorId
     * @return void
     */
    public static function appraise(int $shopId, int $msgId, int $score, int $solve, int $groupId, int $operatorId)
    {

        // 通过msgId获得 sessionId
        $sessionId = (int)ChatGroupHistoryModel::query()
                                               ->where('shopId', $shopId)
                                               ->where('id', $msgId)
                                               ->where('groupId', $groupId)
                                               ->where('type', ChatGroupHistoryModel::TYPE_APPRAISE)
                                               ->value('sessionId');

        if ($sessionId == 0) {
            self::throwErr('该消息不在会话中', 404);
        }

        ChatGroupSessionAppraiseModel::query()->updateOrCreate([
            'uid'       => $operatorId,
            'groupId'   => $groupId,
            'sessionId' => $sessionId
        ], [
            'score' => $score,
            'solve' => $solve
        ]);
    }

    /**
     * 取消呼叫
     * @param int $shopId
     * @param int $groupId
     * @return void
     * @throws Exception
     */
    public static function cancelCall(int $shopId, int $groupId)
    {
        $session = ChatGroupSessionModel::getActiveSession($groupId);
        if (!$session) {
            return;
        }

        if ($session->shopId != $shopId) {
            BaseService::throwErr("门店没有该群聊权限");
        }

        if ($session->serveIn == ChatGroupSessionModel::SERVE_IN_NO) {
            return;
        }

        if ($session->serveIn == ChatGroupSessionModel::SERVE_IN_YES) {
            BaseService::throwErr("客服已介入聊天");
        }

        $session->serveIn = ChatGroupSessionModel::SERVE_IN_NO;
        $session->robotIn = (int)ChatGroupSessionService::getAiSwitch();
        $session->save();

        $obj = (new ChatGroupStructService($groupId, $session->shopId));

        // tips
        $obj->sendMsgStruct(0, '', ChatGroupHistoryModel::TYPE_TIPS, '呼叫已取消')->send();

        // session变更cmd
        $obj->sessionChange($session)->send();

        // 群聊tab数量
        $obj->groupTabNum()->send();
    }

    /**
     * 呼叫客服
     * @param int $shopId
     * @param int $groupId
     * @param bool $action
     * @return void
     * @parame bool $action true主动 false自动
     * @throws Exception
     */
    public static function callServe(int $shopId, int $groupId, bool $action = true, int $userId = 0)
    {
        $closureDo = function () use ($shopId, $groupId, $action, $userId) {
            $start = HolidayModel::WORK_TIME_HOUR_START;
            $end   = HolidayModel::WORK_TIME_HOUR_END;
            // 工作日9:00-18:00才能呼叫
            if (date('H') < $start || date('H') >= $end || !HolidayModel::checkWork()) {

                $aiSwitch = ChatGroupSessionService::getAiSwitch();
                if ($aiSwitch) {
                    if ($action) {
                        $content = "抱歉，当前非人工值班时间，您可以在工作日的 {$start}:00-{$end}:00 呼叫人工客服，紧急问题可直接联系督导~";
                    } else {
                        $content = "很抱歉，小助手暂时无法解决您的问题，您可以在工作日的 {$start}:00-{$end}:00 呼叫人工客服，紧急问题可直接联系督导~";
                    }
                } else {
                    $content = "抱歉，当前非人工值班时间，您可以在工作日的 {$start}:00-{$end}:00 呼叫人工客服，紧急问题可直接联系督导~";
                }

                (new ChatGroupStructService($groupId, $shopId))
                    ->sendMsgStruct(ChatGroupUserModel::KUA_XIAO_FU_USER_ID, '', ChatGroupHistoryModel::TYPE_TEXT,
                        $content, 0, 0, ChatGroupHistoryModel::IS_SEND_AI_NO)
                    ->send();

                BaseService::throwErr("当前时间不在呼叫时间内");
            }

            $session = ChatGroupSessionModel::getActiveSession($groupId);
            if (!$session) {
                if (!$userId) {
                    BaseService::throwErr("当前群聊不存在进行中的会话");
                }

                // 创建新会话
                (new ChatGroupSessionService())->enterSession($shopId, $groupId,
                    ChatGroupSessionService::FROM_APP, $userId);

                $session = ChatGroupSessionModel::getActiveSession($groupId);
            }

            if ($session->shopId != $shopId) {
                BaseService::throwErr("门店没有该群聊权限");
            }

            if ($session->serveIn == ChatGroupSessionModel::SERVE_IN_YES) {
                BaseService::throwErr("客服已介入聊天");
            }

            if ($session->serveIn == ChatGroupSessionModel::SERVE_IN_ING) {
                BaseService::throwErr("正在呼叫中");
            }

            // 群消息通知
            ChatGroupNotifyService::callServeFsNotify($shopId, $groupId);

            // 清空 AI 会话
            ChatGroupAiChatService::clearAiHistory($groupId);

            // 呼叫记录呼叫客服
            ChatGroupSessionService::recordDataStatistics($shopId, $groupId, $session->id, 1,
                ChatGroupDataStatisticsModel::TYPE_CALL);


            $session->serveIn     = ChatGroupSessionModel::SERVE_IN_ING;
            $session->robotIn     = ChatGroupSessionModel::ROBOT_IN_NO;
            $session->serveInTime = time();
            $session->save();

            $obj = (new ChatGroupStructService($groupId, $session->shopId));

            // session变更cmd
            $obj->sessionChange($session)->send();

            // 群聊tab数量
            $obj->groupTabNum()->send();

            // 夸小父消息
            $obj->sendMsgStruct(ChatGroupUserModel::KUA_XIAO_FU_USER_ID, '', ChatGroupHistoryModel::TYPE_TEXT,
                '@all，大家来看下这个问题', 0, 0, ChatGroupHistoryModel::IS_SEND_AI_NO)->send();

            $obj->sendMsgStruct(ChatGroupUserModel::KUA_XIAO_FU_USER_ID, '', ChatGroupHistoryModel::TYPE_TEXT,
                '您可以先在此列出问题，人工介入后会快速为您解答~', 0, 0, ChatGroupHistoryModel::IS_SEND_AI_NO)->send();
        };

        (new NxLock())->nx($closureDo, null,
            NxLock::generateLockKey(__CLASS__ . '_' . __FUNCTION__, ...[$groupId]));

    }

    /**
     * 数据统计呼叫
     *
     * @param int $shopId
     * @param int $groupId
     * @param int $sessionId
     * @param int $statisticData
     * @param int $type
     * @return void
     */
    public static function recordDataStatistics(
        int $shopId,
        int $groupId,
        int $sessionId,
        int $statisticData,
        int $type
    ) {
        (new ChatGroupDataStatisticsModel())->recordDataStatistics($shopId, $groupId, $sessionId, $statisticData,
            $type);
    }

    /**
     * 统计人工介时长
     *
     * @param int $shopId
     * @param int $groupId
     * @param int $sessionId
     * @return void
     */
    public static function recordServeInDataStatistics(
        int $shopId,
        int $groupId,
        int $sessionId
    ) {
        // 客服介入记录统计
        (new ChatGroupDataStatisticsModel())->recordDataStatistics($shopId, $groupId, $sessionId, 1,
            ChatGroupDataStatisticsModel::TYPE_CALL_CUSTOMER);

        // 获取呼叫人工的时间
        $row = ChatGroupDataStatisticsModel::query()
                                           ->where('shopId', $shopId)
                                           ->where('groupId', $groupId)
                                           ->where('sessionId', $sessionId)
                                           ->where('type', ChatGroupDataStatisticsModel::TYPE_CALL)
                                           ->orderByDesc('createdAt')
                                           ->first();

        if (empty($row)) {
            return;
        }

        $duration = time() - $row->createdAt->timestamp;

        (new ChatGroupDataStatisticsModel())->recordDataStatistics($shopId, $groupId, $sessionId, $duration,
            ChatGroupDataStatisticsModel::TYPE_CALL_TIME);


    }

    /**
     * 客服介入
     * @param int $groupId
     * @param int $userId
     * @return void
     * @throws GuzzleException
     */
    public function serveIn(int $groupId, int $userId)
    {
        $user = ChatGroupUserModel::query()
                                  ->where('groupId', $groupId)
                                  ->where('userId', $userId)
                                  ->where('role', ChatGroupUserModel::ROLE_KF)
                                  ->first();
        if (!$user) {
            BaseService::throwErr("您不是群内总部人员");
        }
        $username = $user->alias;

        // 获取/创建一个新会话
        $session = $this->getSession(0, $groupId, self::FROM_WEB, true)['session'];

        if ($session && $session->serveIn == ChatGroupSessionModel::SERVE_IN_YES) {
            BaseService::throwErr("客服已介入聊天");
        }

        if (!$session) {
            BaseService::throwErr("当前群聊不存在进行中的会话");
        }

        // 总部人员未配置昵称
        if (!$username) {
            $username = RmsUserService::getRmsUserInfoByUserIds([$userId], [],
                true)['data'][0]['username'] ?? '';

            // 先自动填充
            $user->alias = $username;
            $user->save();
        }

        $session->serveIn   = ChatGroupSessionModel::SERVE_IN_YES;
        $session->robotIn   = ChatGroupSessionModel::ROBOT_IN_NO;
        $session->serveUid  = $userId;
        $session->serveName = $username;
        $session->save();

        // 客服介入记录介入时间
        ChatGroupSessionService::recordServeInDataStatistics($session->shopId, $groupId, $session->id);

        $obj = (new ChatGroupStructService($groupId, $session->shopId));

        $obj->sendMsgStruct(0, '',
            ChatGroupHistoryModel::TYPE_TIPS, "在线客服{$username}已介入",
            0, 0, ChatGroupHistoryModel::IS_SEND_AI_NO
        )->send();

        $obj->sessionChange($session)->send();

        // 群聊tab数量
        $obj->groupTabNum()->send();
    }

    /**
     * 关闭会话
     * @param int $shopId
     * @param int $groupId
     * @param bool $isAuto
     * @return void
     * @throws Exception
     */
    public static function close(int $shopId, int $groupId, bool $isAuto = false)
    {
        // 获得活动的会话
        $sessionModel = ChatGroupSessionModel::getActiveSession($groupId);

        if (null == $sessionModel || $shopId != $sessionModel->shopId) {
            self::throwErr('门店群聊不存在', 404);
        }

        // 修改会话状态
        $sessionModel->status  = ChatGroupSessionModel::STATUS_CLOSE;
        $sessionModel->robotIn = (int)self::getAiSwitch();
        $sessionModel->serveIn = ChatGroupSessionModel::SERVE_IN_NO;
        $sessionModel->save();

        // 发送卡片消息
        if (!$isAuto) {
            // 获得所有参与会话的人
            $userIds = ChatGroupHistoryModel::query()
                                            ->where('sessionId', $sessionModel->id)
                                            ->pluck('senderUid')
                                            ->unique()
                                            ->values()
                                            ->toArray();

            // 获得门店下员工的Id
            $staffUserIds = ChatGroupUserModel::query()
                                              ->where('shopId', $shopId)
                                              ->where('groupId', $groupId)
                                              ->whereIn('role',
                                                  [ChatGroupUserModel::ROLE_EMPLOYEE, ChatGroupUserModel::ROLE_BOSS])
                                              ->pluck('userId')
                                              ->toArray();

            $users = collect(array_intersect($userIds, $staffUserIds))->unique()->map(function ($userId) {
                return [
                    'user_id' => $userId,
                    'score'   => 0,
                    'solve'   => 0,
                ];
            })->values()->toArray();

            // 评价卡数据写入
            $insertData = [];
            foreach ($users as $user) {
                if ($user['user_id'] == ChatGroupUserModel::KUA_XIAO_FU_USER_ID) {
                    continue;
                }

                $insertData[] = [
                    'sessionId' => $sessionModel->id,
                    'shopId'    => $shopId,
                    'groupId'   => $groupId,
                    'uid'       => $user['user_id'],
                    'createdAt' => time()
                ];
            }

            ChatGroupSessionAppraiseModel::query()->insert($insertData);

            if ($users) {
                (new ChatGroupStructService($groupId, $shopId))
                    ->sendMsgStruct(0, '', ChatGroupHistoryModel::TYPE_APPRAISE, $users,
                        0, $sessionModel->id, ChatGroupHistoryModel::IS_SEND_AI_NO)->send();
            }
        }
        self::closeSessionChange($sessionModel);
    }

    public static function closeSessionChange(ChatGroupSessionModel $chatGroupSessionModel)
    {
        $obj = (new ChatGroupStructService($chatGroupSessionModel->groupId, $chatGroupSessionModel->shopId));

        // 发送会话变更消息
        $obj->sessionChange($chatGroupSessionModel)->send();

        // 群聊tab数量
        $obj->groupTabNum()->send();

        // 发送tips
        (new ChatGroupStructService($chatGroupSessionModel->groupId, $chatGroupSessionModel->shopId))
            ->sendMsgStruct(0, '', ChatGroupHistoryModel::TYPE_TIPS, '会话已关闭', 0, 0,
                ChatGroupHistoryModel::IS_SEND_AI_NO)
            ->send();
    }

    /**
     * ai机器人开关
     * @return bool
     */
    public static function getAiSwitch(): bool
    {
        return Cache::remember('chat_group_ai_switch', 60, function () {
            return (bool)ConfigModel::getValue('chatGroup', 'aiSwitch');
        });
    }

    /**
     * 发送常见问题
     * @param int $shopId
     * @param int $groupId
     * @return void
     * @throws Exception
     */
    public static function sendFaq(int $shopId, int $groupId, int $userId)
    {
        // 判断是否在会话中 不在会话中创建会话
        $session = ChatGroupSessionModel::getActiveSession($groupId);

        if (empty($session)) {
            (new ChatGroupSessionService())->enterSession($shopId, $groupId,
                ChatGroupSessionService::FROM_APP, $userId);
        } else {
            (new ChatGroupStructService($groupId, $shopId))
                ->sendMsgStruct(ChatGroupUserModel::KUA_XIAO_FU_USER_ID, '', ChatGroupHistoryModel::TYPE_FAQ_V2, [])
                ->send();
        }
    }

    /*
     * 获得常见问题答案
     * @param string $indexNumber
     * @return array
     */
    public static function faqAnswer(string $indexNumber): array
    {
        $faqAnswer = ChatGroupFAQModel::query()
                                      ->where('indexNumber', $indexNumber)
                                      ->first();

        if ($faqAnswer == null) {
            self::throwErr('暂无该常见问题的答案', 404);
        }

        $data = [];

        $attachment = $faqAnswer->attachment ? json_decode($faqAnswer->attachment, true) : [];

        foreach ($attachment as $file) {
            if (!isset($file['type']) || !isset($file['url'])) {
                continue;
            }
            $data[$file['type']] = $file['url'];
        }

        return array_merge([
            'title' => ChatGroupFAQModel::getQuestionByIndexNumber($indexNumber),
            'text'  => $faqAnswer->answer,
            'id'    => $faqAnswer->id,
        ], $data);
    }

    /**
     * 问题答案-增加有用、无用操作
     * @param int $id
     * @param int $type
     * @param int $shopId
     * @param int $groupId
     * @param int $msgId
     * @return array
     */
    public static function faqAnswerOperate(int $id, int $type, int $shopId, int $groupId, int $msgId,int $userId): array
    {
        $sessionId = $isAi = 0;
        $faqAnswer = null;
        $content   = [];
        if ($id) {// 问题id
            $faqAnswer = ChatGroupFAQModel::query()
                ->where('id', $id)
                ->first();
        } elseif ($msgId) {// 聊天记录
            $msgInfo = ChatGroupHistoryModel::query()
                ->where('id', $msgId)
                ->first();
            if (!$msgInfo) {
                self::throwErr('暂无该消息', 404);
            }
            $groupId     = $msgInfo->groupId;                                      // 群聊id
            $sessionId   = $msgInfo->sessionId;                                    // 会话id
            $content     = json_decode($msgInfo->content ?? '', true) ?? [];       // 消息内容
            $indexNumber = $content['btn'][0]['params']['indexNumber'] ?? '';      // 问题index
            $isAi        = (int)($content['isAiAnswer'] ?? 0);                     // 是否是AI答案卡
            if (!$indexNumber) {
                self::throwErr('未关联到常见问题index', 404);
            }
            $faqAnswer = ChatGroupFAQModel::query()
                ->where('indexNumber', $indexNumber)
                ->first();
        }

        if ($faqAnswer == null) {
            self::throwErr('暂无该常见问题', 404);
        }
        $typeStatistics = 0;

        DB::beginTransaction();
        try {

            switch ($type) {
                case ChatGroupFAQModel::TYPE_USE_FULL:// 有用
                    $faqAnswer->usefulNum = DB::raw('usefulNum+1');
                    if ($isAi) {
                        $typeStatistics = ChatGroupDataStatisticsModel::TYPE_FAQ_ANSWER_USE_FULL_AI;
                    } else {
                        $typeStatistics = ChatGroupDataStatisticsModel::TYPE_FAQ_ANSWER_USE_FULL;
                    }
                    break;
                case ChatGroupFAQModel::TYPE_USE_LESS:// 无用
                    $faqAnswer->uselessNum = DB::raw('uselessNum+1');
                    if ($isAi) {
                        $typeStatistics = ChatGroupDataStatisticsModel::TYPE_FAQ_ANSWER_USE_LESS_AI;
                    } else {
                        $typeStatistics = ChatGroupDataStatisticsModel::TYPE_FAQ_ANSWER_USE_LESS;
                    }
                    break;
                default:
                    self::throwErr('操作类型错误', 400);
            }
            $faqAnswer->save();

            // 修改聊天记录中哪些人点了有用和无用
            if ($msgId && $content && isset($msgInfo)) {
                $userAppraise = [
                    'user_id' => $userId,
                    'solve'   => $type,
                ];
                if (isset($content['userAppraise']) && $content['userAppraise']) {
                    $content['userAppraise'] = array_merge(
                        $content['userAppraise'], [$userAppraise]
                    );
                } else {
                    $content['userAppraise'] = [$userAppraise];
                }
                $msgInfo->content = json_encode($content, JSON_UNESCAPED_UNICODE);
                $msgInfo->save();
            }

            // 客服数据表统计
            (new ChatGroupDataStatisticsModel)->recordDataStatistics($shopId, $groupId, $sessionId, 1, $typeStatistics);

            DB::commit();

        } catch (Exception $e) {
            Log::info(
                'faqAnswerOperateErr', [
                    "id"      => $id,
                    'type'    => $type,
                    'shopId'  => $shopId,
                    'groupId' => $groupId,
                    'msgId'   => $msgId,
                    'msg'     => $e->getMessage(),
                ]
            );
            DB::rollBack();
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, '问题点赞操作失败');
        }
        return [];
    }
}
